package com.piece.admin.event;

import com.piece.admin.model.TbSysUser;
import com.piece.core.framework.support.dto.PayloadDTO;
import com.piece.core.framework.util.message.MessageFactory;
import com.piece.core.mongo.entity.MongoMessageLog;
import com.piece.core.framework.util.string.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

@Slf4j
@Component
public class SystemPostEventHandler implements ApplicationListener<SystemPostEvent> {

    @Resource
    private MessageFactory messageFactory;

    @Async
    @Override
    public void onApplicationEvent(SystemPostEvent event) {
        if (null == event) {
            return;
        }

        TbSysUser user = event.getUser();
        MongoMessageLog messageLog = new MongoMessageLog();
        messageLog.setEntity(JsonUtil.toJson(user));

        switch (event.getAction()) {
            case SystemPostEvent.ACTION_REGISTER_VALIDATE:
                messageLog.setTitle("注册确认提醒");
                messageLog.setMethod("systemOperatorEvent.registerConfirmMessage");
                break;
            case SystemPostEvent.ACTION_REGISTER_SUCCESS:
                messageLog.setTitle("注册成功提醒");
                messageLog.setMethod("systemOperatorEvent.registerMessage");
                break;
        }

        try {
            PayloadDTO payload = new PayloadDTO();
            payload.setEntity(JsonUtil.toJson(messageLog));
            messageFactory.get().send(payload);
        } catch (Exception e) {
            log.error("系统事件发送消息失败：{}", e.getMessage());
        }
    }
}
